// wxml
//
// <form
// bindsubmit="_mtFormSubmit"
// bindreset="_mtFormReset">
//   <input type="text" name="name"/>
//   <button
// form-type="submit"
// custom-class="a-btn-default">submit
//   </button>
//   </form>

// js
//
// const mtFormBehavior = require('../../behaviors/mt-form.behavior')

// data
// formValid
// formDisabled

// handle
//
// mtValidateSchema 返回每次调用的schema
// mtOnFormSubmit 当form表单提交时回调

const app = getApp()

let validate = app.validate

module.exports = Behavior({
  behaviors: [],
  properties: {},
  data: {
    _mtFormData: {},
    _mtFormValid: false,
    _mtFormValidor: {},
    _mtFormScheme: {},
    _mtFormValue: {},
    _mtTmpLocked: false,
    formValid: false,
    formDisabled: true
  },
  attached: function () {
  },
  methods: {
    mtGetFormData() {
      return this.data._mtFormData
    },
    mtFormLock(v) {
      this.setData({
        _mtTmpLocked: v
      })
    },
    mtValidate(value, cb, append) {
      this._mtValidate(value, (errors, fields) => {
        cb(value, !errors, {
          fields,
          errors,
          ...append
        })
      })
    },
    mtValidateLive(cb) {
      let value = this.data._mtFormData
      this.mtValidate(value, cb)
    },
    mtHasError(name, errors) {
      let r = false
      if (Array.isArray(errors) && errors.length > 0) {
        r = errors.some(v => {
          return v.field === name
        })
      }
      return r
    },
    _mtInitModel(name, data) {
      let r = {}
      for (let key in data) {
        r[name + '.' + key] = data[key]
      }
      this.setData(Object.assign({
        _mtFormData: data,
      }, r))
    },
    _mtHandleChange(e) {
      let { mtkey } = e.target.dataset
      if (mtkey) {
        this.setData({
          ['_mtFormData.' + mtkey]: e.detail
        })
      }
      if (this.mtOnChange) {
        this.mtOnChange(this.data._mtFormData, mtkey)
      }
    },
    _mtFormSubmit(e) {
      let value = e.detail.value
      this.mtValidate(value, (value, valid, res) => {
        if (!this.data._mtTmpLocked && this.mtOnFormSubmit) {
          this.mtFormLock(true)
          this.mtOnFormSubmit(value, valid, res)
        }
      }, { e })
    },
    _mtFormReset() {
      if (this.mtOnFormReset) {
        this.mtOnFormReset()
      }
    },
    _mtValidate(value, cb) {
      if (!this.mtValidateSchema) {
        console.error('not validate schema')
      }
      let _mtFormScheme = this.mtValidateSchema(value)
      validate(value, _mtFormScheme, cb)
    },
    _mtSetValidaemethods(othervalidate) {
      validate = othervalidate
    },
    mtResetModel(change) {
      if (!this.mtModel) {
        console.error('not validate schema')
      }
      this.setData(Object.assign(
        this.mtModel(),
        change
      ))
    }
  },
})
